package net.pet.util.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.pet.commons.helper.SessionHelper;
import net.pet.dto.admin.AdminUser;
import net.pet.dto.admin.Resource;

/**
 * Servlet Filter implementation class AuthFilter
 */
public class AuthFilter extends AbstractHttpFilter {
	private static final String noFilter = "/left.htm,/right.htm,/main.htm,/top.htm,/homepage.htm,/welcome.htm";
	@Override
	protected void doFilter(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if(isFilterPattern(request)){
			chain.doFilter(request, response);
		}else{
			if(hasLogin(request,response)){
	        	if(hasAuthority(request)){
	        		chain.doFilter(request, response);
	        	}else{
	        		response.sendError(HttpServletResponse.SC_FORBIDDEN, 
	        	                "Not have authority to visit: " + getVisitUri(request));;
	        	}
	        }else{
	        	response.sendRedirect(request.getContextPath()+"/index.htm");  
	        }  
		}
        
	}
	private boolean hasAuthority(HttpServletRequest request){
		String uri = getVisitUri(request);
		if(uri == null) return false;
		if(noFilter(uri)) return true;
		AdminUser adminUser = SessionHelper.getAdminUser(request);
		for(Resource resource : adminUser.getResourceList()){
			if(uri.equals(resource.getResourceUrl())){
				return true;
			}
		}
		return false;
	}
	/**
	 * 判断页面在登陆后,不需要验证权限
	 * @param uri
	 * @return
	 */
	private boolean noFilter(String uri) {
		//这里就不写配置文件了，直接写成固定值
		
		if(noFilter.indexOf(uri)>=0){
			return true;
		}
		return false;
	}
	private boolean hasLogin(HttpServletRequest request, HttpServletResponse response) {
        AdminUser adminUser = SessionHelper.getAdminUser(request);
        if (adminUser != null) {
            return true;
        } else {
            return false;
        }
    }

}
